'''

Case Type： 数据库系统
Case Name： 一个备节点磁盘满，分别在两个节点进行主备切换
Create At:  2020/07/25
@zou_jialiang0505328126
Descption:  1.备节点A注入磁盘满故障2.在备节点A上主备切换3.在备节点B上主备切换4.备节点A清除故障5.备节点B更新动态配置文件重启集群6.查询集群状态7.在备节点B（新的主节点）上创建表并插入数据8.在原主节点（现备节点）上查询改表

history：
created： 2020/07/25  created by @wan005
'''
import os
import unittest
from yat.test import Node
import time
import threading
import queue
from yat.test import macro
import sys

sys.path.append(sys.path[0] + "/../")
from testcase.utils.Logger import Logger
from testcase.utils.Constant import Constant
from testcase.utils.Common import Common
from testcase.utils.CommonSH import *

logger = Logger()
common = Common()
commonshpri = CommonSH('PrimaryDbUser')
commonshsta1 = CommonSH('Standby1DbUser')
commonshsta2 = CommonSH('Standby2DbUser')


class Disk_full(unittest.TestCase):
    dbPrimaryUserNode = Node(node='PrimaryDbUser')
    dbPrimaryRootNode = Node(node='PrimaryRoot')
    dbStandby1UserNode = Node(node='Standby1DbUser')
    dbStandby2UserNode = Node(node='Standby2DbUser')
    dbStandby1RootNode = Node(node='Standby1Root')
    DB_INSTANCE_PATH = macro.DB_INSTANCE_PATH
    DB_ENV_PATH = macro.DB_ENV_PATH
    PRIMARY_NORMAL = Constant.PRIMARY_NORMAL
    STANDBY_NORMAL = Constant.STANDBY_NORMAL
    CREATE_TABLE_SUCCESS = Constant.CREATE_TABLE_SUCCESS
    DROP_TABLE_SUCCESS = Constant.DROP_TABLE_SUCCESS
    dump_file_name = 'test_pid.tar'
    CFE_PATH = macro.CFE_PATH
    DB_DISK_NAME = ''
    DISK_FULL_MSG = Constant.DISK_FULL_MSG
    RESTORE_SUCCESS_MSG = Constant.RESTORE_SUCCESS_MSG
    RESTART_SUCCESS_MSG = Constant.RESTART_SUCCESS_MSG
    SWITCHOVER_SUCCESS_MSG = Constant.SWITCHOVER_SUCCESS_MSG
    REFRESHCONF_SUCCESS_MSG = Constant.REFRESHCONF_SUCCESS_MSG
    nodes_tuple = ('PrimaryDbUser', 'Standby1DbUser', 'Standby2DbUser')

    @RestartDbCluster(*nodes_tuple)
    def setUp(self):
        logger.info("-----------this is setup-----------")
        logger.info('------------Opengauss_Reliability_Dbsys_Case137.py start------------')

    def test_disk_full(self):
        logger.info("-----------get standby disk name -----------")
        cmd = f"df -h {macro.DB_INSTANCE_PATH}"
        logger.info(cmd)
        msg = self.dbStandby1RootNode.sh(cmd).result()
        logger.info(msg)
        self.DB_DISK_NAME = msg.splitlines()[-1].split()[0].strip()

        logger.info("-----------standby1 disk full -----------")
        cfediskCmd = '''
            {cfe_path}/cfe  "inject  rfile_full (diskname)  values  ({diskname})"'''.format(cfe_path=self.CFE_PATH,
                                                                                            diskname=self.DB_DISK_NAME)
        tmp = self.dbStandby1RootNode.sh(cfediskCmd).result()
        logger.info(tmp)

        logger.info("-----------standby1 switchover-----------")
        switchoverCmd = '''
                source {source_path};
                gs_ctl switchover  -D {DN_PATH}'''.format(source_path=self.DB_ENV_PATH, DN_PATH=self.DB_INSTANCE_PATH)
        switchoverMsg = self.dbStandby1UserNode.sh(switchoverCmd).result()
        logger.info(switchoverMsg)
        self.assertTrue(switchoverMsg.find(self.DISK_FULL_MSG) > -1)

        time.sleep(5)

        logger.info("-----------standby2 switchover-----------")
        switchoverCmd = '''
                source {source_path};
                gs_ctl switchover  -D {DN_PATH};
                gs_om -t refreshconf'''.format(source_path=self.DB_ENV_PATH, DN_PATH=self.DB_INSTANCE_PATH)
        switchoverMsg = self.dbStandby2UserNode.sh(switchoverCmd).result()
        logger.info(switchoverMsg)
        self.assertTrue(switchoverMsg.find(self.DISK_FULL_MSG) > -1)
        self.assertTrue(switchoverMsg.find(self.SWITCHOVER_SUCCESS_MSG) > -1)

        time.sleep(5)

        logger.info("-----------standby1 clean disk-----------")
        cfediskCmd = '''
            {cfe_path}/cfe "clean  rfile_full  where(diskname={diskname})"'''.format(cfe_path=self.CFE_PATH,
                                                                                     diskname=self.DB_DISK_NAME)
        tmp = self.dbStandby1RootNode.sh(cfediskCmd).result()
        logger.info(tmp)

        time.sleep(5)

        logger.info("----------- standby2 refreshconf-----------")
        refreshconfCmd = '''
                source {source_path};
                gs_om -t refreshconf;
                gs_om -t start'''.format(source_path=self.DB_ENV_PATH)
        refreshconfMsg = self.dbStandby2UserNode.sh(refreshconfCmd).result()
        logger.info(refreshconfMsg)
        self.assertTrue(refreshconfMsg.find(self.REFRESHCONF_SUCCESS_MSG) > -1)

        logger.info("-----------check opengauss status-----------")
        checkCmd = '''
            source {source_path};
            gs_om -t status --detail'''.format(source_path=self.DB_ENV_PATH)
        checktMsg = self.dbPrimaryUserNode.sh(checkCmd).result()
        logger.info(checktMsg)
        self.assertTrue(checktMsg.find(self.PRIMARY_NORMAL) > -1)
        self.assertTrue(checktMsg.find(self.PRIMARY_NORMAL) > -1)

        logger.info("-----------create table &insert data-----------")
        createMsg = commonshsta2.executDbSql(
            'drop table if exists test_table55;create table test_table55(id int,name varchar(20));')
        logger.info(createMsg)
        insert_msg = commonshsta2.executDbSql(
            'insert into test_table55 values(1,\'aaa\');insert into test_table55 values(2,\'aaa\');')
        logger.info(insert_msg)
        self.assertTrue(createMsg.find(self.CREATE_TABLE_SUCCESS) > -1)

        logger.info("-----------check data consistency-----------")
        flag = commonshsta1.check_data_consistency()
        self.assertTrue(flag)
        logger.info("-----------query data consistency-----------")
        result = commonshsta1.executDbSql('select count(*) from test_table55;')
        logger.info(result)
        self.assertTrue(result.find('2') > -1)
        result = commonshpri.executDbSql('select count(*) from test_table55;')
        logger.info(result)
        self.assertTrue(result.find('2') > -1)

    def tearDown(self):
        logger.info('----------------this is tearDown-----------------------')
        logger.info("-----------clean disk-----------")
        cfediskCmd = '''
            {cfe_path}/cfe "clean  rfile_full  where(diskname={diskname})"'''.format(cfe_path=self.CFE_PATH,
                                                                                     diskname=self.DB_DISK_NAME)
        tmp = self.dbStandby1RootNode.sh(cfediskCmd).result()
        logger.info(tmp)
        logger.info('----------------switchover restore original primary-----------------------')

        logger.info("-----------drop table -----------")
        createMsg = commonshsta2.executDbSql('create table test_table55(id int,name varchar(20));')
        commonshsta2.executDbSql('drop table test_table55 ;')

        switchoverCmd = '''
        source {source_path};
        gs_ctl switchover  -D {DN_PATH};
        gs_om -t refreshconf'''.format(source_path=self.DB_ENV_PATH, DN_PATH=self.DB_INSTANCE_PATH)
        switchoverMsg = self.dbPrimaryUserNode.sh(switchoverCmd).result()
